package com.icinfo.cloud.provider.common.utils;

import com.icinfo.cloud.provider.common.constant.Constant;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 描述：base64转文件工具
 *
 * @author xiangyuyu
 * @date 2022-03-02 09:14
 */
public class Base64ToMultipartFileUtil implements MultipartFile {

    private final byte[] fileContent;
    private final String extension;
    private final String contentType;

    public Base64ToMultipartFileUtil(String base64, String extension, String contentType) {
        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        this.extension = extension;
        this.contentType = contentType;
    }


    public Base64ToMultipartFileUtil(String base64, String dataUri) {
        this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        this.extension = dataUri.split(";")[0].split("/")[1];
        this.contentType = dataUri.split(";")[0].split(":")[1];
    }

    public Base64ToMultipartFileUtil(String base64String) {
        //检测是否含有base64,文件头
        String dataUri = base64String;
        if (base64String.lastIndexOf(Constant.STRING_COMMA) > -1) {
            dataUri = base64String.substring(0, base64String.lastIndexOf(Constant.STRING_COMMA) + 1);
            base64String = base64String.substring(base64String.lastIndexOf(Constant.STRING_COMMA) + 1);
        }
        this.fileContent = Base64.getDecoder().decode(base64String.getBytes(StandardCharsets.UTF_8));
        this.extension = dataUri.split(";")[0].split("/")[1];
        String[] tempStr = dataUri.split(";")[0].split(":");
        if(!ObjectUtils.isEmpty(tempStr) && tempStr.length > 1) {
            this.contentType = dataUri.split(";")[0].split(":")[1];
        } else {
            this.contentType = "";
        }
    }

    @Override
    public String getName() {
        return "param_" + System.currentTimeMillis();
    }

    @Override
    public String getOriginalFilename() {
        return "file_" + System.currentTimeMillis() + "." + extension;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return fileContent == null || fileContent.length == 0;
    }

    @Override
    public long getSize() {
        return fileContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return fileContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(fileContent);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(fileContent);
            fos.close();
        }
    }
}
